package view;


import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;

import model.Setor;
import control.ControllersDaos;


public class VSetor extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JPanel contentPane;
	private JTextField tf_GetNome; 
	private JTextField tf_GetResp;
	private JFormattedTextField tf_GetSala;
	private JFormattedTextField tf_GetCod;
	private JButton btnPesquisar;
	private JButton btnNovo;
	private JButton btnExcluir;
	private JButton btnAlterar;
	private JButton btnInserir;
	private Setor	setorN 		= new Setor(0, null, null, 0);
	//private SetorCRUD setorIn   = new SetorCRUD();
	private ControllersDaos controller;
	private VPrincipal telaAnt;
	private JButton btnCancelar;
	
	/**
	 * Launch the application.
	 */
	

/*	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					VSetor frame = new VSetor();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
*/
	private  void LimparTela(){
		tf_GetCod.setText("");
		tf_GetNome.setText("");
		tf_GetResp.setText("");
		tf_GetSala.setText("");
		
		btnCancelar.setVisible(false);
		btnCancelar.setSelected(false);
		contentPane.remove(btnCancelar);

		
	}

	private  void AtivarCampoBotao(){
		tf_GetCod.setEnabled(true);
		tf_GetNome.setEnabled(true);
		tf_GetResp.setEnabled(true);
		tf_GetSala.setEnabled(true);
		btnAlterar.setEnabled(true);
		btnInserir.setEnabled(true);
		btnExcluir.setEnabled(true);
		btnNovo.setEnabled(true);
		btnPesquisar.setEnabled(true);
			
	}
	
	private void BloquearCampos(){
		tf_GetCod.setEnabled(true);
		tf_GetCod.setEditable(true);
		tf_GetCod.setVisible(true);
		tf_GetNome.setEnabled(false);
		tf_GetResp.setEnabled(false);
		tf_GetSala.setEnabled(false);
		btnAlterar.setEnabled(false);
		btnInserir.setEnabled(false);
		btnExcluir.setEnabled(false);
		btnNovo.setEnabled(true);
		btnPesquisar.setEnabled(true);
		
	}

	/**
	 * Create the frame.
	 */
	public VSetor(VPrincipal telaAnterior, ControllersDaos controlador) {
        this();
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        telaAnt    = telaAnterior;
        controller = controlador;
	}
	
	private VSetor() {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosed(WindowEvent arg0) {
				telaAnt.setVisible(true);
			}
		});
		setTitle("Cadastro Setor");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 500, 340);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);
		setContentPane(contentPane);
		
		JLabel lblCodigo = new JLabel("C\u00F3digo:");
		lblCodigo.setFont(new Font("Calisto MT", Font.BOLD, 12));
		lblCodigo.setBounds(10, 15, 46, 14);
		contentPane.add(lblCodigo);
		
		JLabel lblNome = new JLabel("Nome:");
		lblNome.setFont(new Font("Calisto MT", Font.BOLD, 12));
		lblNome.setBounds(10, 61, 46, 14);
		contentPane.add(lblNome);
		
		tf_GetNome = new JTextField();
		tf_GetNome.setEnabled(false);
		tf_GetNome.setBounds(10, 77, 311, 20);
		contentPane.add(tf_GetNome);
		tf_GetNome.setColumns(10);
		
		JLabel lblResponsavel = new JLabel("Respons\u00E1vel:");
		lblResponsavel.setFont(new Font("Calisto MT", Font.BOLD, 12));
		lblResponsavel.setBounds(10, 108, 79, 14);
		contentPane.add(lblResponsavel);
		
		tf_GetResp = new JTextField();
		tf_GetResp.setEnabled(false);
		tf_GetResp.setColumns(10);
		tf_GetResp.setBounds(10, 126, 311, 20);
		contentPane.add(tf_GetResp);
		
		JLabel lblSala = new JLabel("N\u00FAmero Sala:");
		lblSala.setFont(new Font("Calisto MT", Font.BOLD, 12));
		lblSala.setBounds(10, 161, 79, 14);
		contentPane.add(lblSala);
		
		tf_GetSala = new JFormattedTextField(NovaMask("#####"));
		tf_GetSala.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
		tf_GetSala.setFocusLostBehavior(JFormattedTextField.PERSIST);
		tf_GetSala.setEnabled(false);
		tf_GetSala.setBounds(10, 186, 46, 20);
		contentPane.add(tf_GetSala);
		tf_GetSala.setColumns(10);
		
		btnInserir = new JButton("Inserir");
		btnInserir.setEnabled(false);
		btnInserir.setMnemonic(KeyEvent.VK_C);
		btnInserir.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnInserir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String 		campoCod  = tf_GetCod.getText().trim().toUpperCase();
		        String 		campoNome = tf_GetNome.getText().trim().toUpperCase();
		        String 		campoResp = tf_GetResp.getText().trim().toUpperCase();
		        String 		campoSala = tf_GetSala.getText().trim();
		        Integer 	nSala 	  = 0;
		        Integer 	nCod      = 0;
		        		        
		        if (campoNome == null || campoNome.equals("")||campoResp == null || campoResp.equals("")) {
		        	JOptionPane.showMessageDialog(null,"Verifique os campos");
		        }else{
		        	try{
		        		if(!campoSala.isEmpty())
		        		nSala   = Integer.parseInt(campoSala);
		        		
		        		nCod    = Integer.parseInt(campoCod );
		        		setorN  = new Setor(nCod,campoNome, campoResp, nSala);
		        		//setorIn.inserirSetor(setorN);
		        		controller.inserirSetor(setorN);
		        		JOptionPane.showMessageDialog(null, "Setor Cadastrado Com SUCESSO!!","INFORM��O",JOptionPane.INFORMATION_MESSAGE);
		        		LimparTela();
		        		
		        		BloquearCampos();
		        	}catch (NumberFormatException ex){
		        		JOptionPane.showMessageDialog(null, "Problema no Casdastro do Setor, Verifique os Campos");
		        		ex.printStackTrace();
		        	} catch (ClassNotFoundException ex) {
		        		JOptionPane.showMessageDialog(null, "Problema na Casdastro do Setor");
		        		ex.printStackTrace();
					} catch (SQLException ex) {
						JOptionPane.showMessageDialog(null, "Problema na Casdastro do Setor no Banco.");
						ex.printStackTrace();
					}
		        	
		        
		        }
				
				
			}
		});
		btnInserir.setBounds(169, 257, 89, 34);
		contentPane.add(btnInserir);
		
		btnNovo = new JButton("Novo");
		btnNovo.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnNovo.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				try{
					//tf_GetCod.setText(String.valueOf(setorIn.proximoIdSetor()));
					tf_GetCod.setText(String.valueOf(controller.proximoIdSetor()));
					AtivarCampoBotao();
					tf_GetCod.setEditable(false);
					btnNovo.setEnabled(false);
					btnPesquisar.setEnabled(false);
					btnExcluir.setEnabled(false);
					btnAlterar.setEnabled(false);
					AtivarBtnCancelar();
	        	} catch (ClassNotFoundException ex) {
	        		JOptionPane.showMessageDialog(null, "Problema na solicita��o do Setor");
	        		ex.printStackTrace();
				} catch (SQLException ex) {
					JOptionPane.showMessageDialog(null, "Problema na solicita��o do Setor no Banco.");
					ex.printStackTrace();
				}
			}
		});
		btnNovo.setHorizontalAlignment(SwingConstants.LEFT);
		btnNovo.setIcon(new ImageIcon(VSetor.class.getResource("/imagens/Novo.jpg")));
		btnNovo.setMnemonic(KeyEvent.VK_N);
		btnNovo.setBounds(10, 257, 89, 34);
		contentPane.add(btnNovo);
		
		btnAlterar = new JButton("Alterar");
		btnAlterar.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnAlterar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String 		campoCod  = tf_GetCod.getText().trim().toUpperCase();
		        String 		campoNome = tf_GetNome.getText().trim().toUpperCase();
		        String 		campoResp = tf_GetResp.getText().trim().toUpperCase();
		        String 		campoSala = tf_GetSala.getText().trim();
		        Integer 	nSala 	  = 0;
		        Integer 	nCod      = 0;
		        		        
		        if (campoNome == null || campoNome.equals("")||campoResp == null || campoResp.equals("")) {
		        	JOptionPane.showMessageDialog(null,"Verifique os campos");
		        }else{
		        	try{
		        		if(!campoSala.isEmpty())
		        		nSala   = Integer.parseInt(campoSala);
		        		
		        		nCod    = Integer.parseInt(campoCod );
		        		setorN  = new Setor(nCod,campoNome, campoResp, nSala);
		        		//setorIn.alterarSetor(setorN);
		        		controller.alterarSetor(setorN);
		        		JOptionPane.showMessageDialog(null, "Setor Alterado Com SUCESSO!!","INFORM��O",JOptionPane.INFORMATION_MESSAGE);
		        		LimparTela();
		        		BloquearCampos();
		        	}catch (NumberFormatException ex){
		        		JOptionPane.showMessageDialog(null, "Problema na Altera��o do Setor, Verifique os Campos");
		        		ex.printStackTrace();
		        	} catch (ClassNotFoundException ex) {
		        		JOptionPane.showMessageDialog(null, "Problema na Altera��o do Setor");
		        		ex.printStackTrace();
					} catch (SQLException ex) {
						JOptionPane.showMessageDialog(null, "Problema na Altera��o do Setor no Banco.");
						ex.printStackTrace();
					}
		        	
		        
		        }
				
			}
		});
		btnAlterar.setEnabled(false);
		btnAlterar.setMnemonic(KeyEvent.VK_A);
		btnAlterar.setBounds(268, 257, 89, 34);
		contentPane.add(btnAlterar);
		
		tf_GetCod = new JFormattedTextField(NovaMask("#####")) ;
		tf_GetCod.setFocusLostBehavior(JFormattedTextField.PERSIST);
		tf_GetCod.setBounds(10, 36, 46, 20);
		contentPane.add(tf_GetCod);
		tf_GetCod.setColumns(10);
		
		btnPesquisar = new JButton("Pesquisar");
		btnPesquisar.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnPesquisar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Pesquisar();
			}

		});
		btnPesquisar.setIcon(new ImageIcon(VSetor.class.getResource("/imagens/Pesquisar.png")));
		btnPesquisar.setBounds(337, 22, 137, 34);
		contentPane.add(btnPesquisar);
		
		btnExcluir = new JButton("Excluir");
		btnExcluir.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnExcluir.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String 	campoCod  = tf_GetCod.getText().trim().toUpperCase();
				Integer nCod=0;

				try{
					nCod      = Integer.parseInt(campoCod );
					setorN.setId(nCod);
					//setorIn.deletarSetor(setorN);
					controller.deletarSetor(setorN);
	        		JOptionPane.showMessageDialog(null, "Setor Exlu�do Com SUCESSO!!","INFORM��O",JOptionPane.INFORMATION_MESSAGE);

	        		LimparTela();
	        		BloquearCampos();
					
				}catch (NumberFormatException ex){
					JOptionPane.showMessageDialog(null, "Problema na Exclus�o do Setor, Verifique os Campos");
					ex.printStackTrace();
				} catch (ClassNotFoundException ex) {
					JOptionPane.showMessageDialog(null, "Problema na Exclus�o do Setor");
					ex.printStackTrace();
				} catch (SQLException ex) {
					JOptionPane.showMessageDialog(null, "Problema na Exclus�o do Setor no Banco.");
					ex.printStackTrace();
				}

			}
		});
		btnExcluir.setEnabled(false);
		btnExcluir.setIcon(new ImageIcon(VSetor.class.getResource("/imagens/excluir.jpg")));
		btnExcluir.setBounds(367, 257, 107, 34);
		contentPane.add(btnExcluir);
		BloquearCampos();
		
		
	}
	private void Pesquisar() {
		String 	campoCod  = tf_GetCod.getText().trim().toUpperCase();
		Integer nCod=0;
		ArrayList<Setor> listSetor = new ArrayList<Setor>() ;
		boolean encontrou = false;
		if (campoCod == null || campoCod.equals("")) {
			JOptionPane.showMessageDialog(null, "Informe um C�digo para Pesquisar");
		}else{
			try{
				nCod      = Integer.parseInt(campoCod );
				//listSetor = setorIn.listarSetor();
				listSetor = controller.listarSetor();
				for (Setor setor : listSetor) {
					if (nCod == setor.getId()){
						tf_GetNome.setText(setor.getNome());
						tf_GetResp.setText(setor.getResponsavel());
						tf_GetSala.setText(setor.getSala()+"");
						encontrou = true;
					}
				}
				if (encontrou){
					AtivarCampoBotao();
					tf_GetCod.setEditable(false);
					btnInserir.setEnabled(false);
					btnPesquisar.setEnabled(false);
					
					AtivarBtnCancelar();
				
				}else{
					JOptionPane.showMessageDialog(null, "Nenhum Registro Encontrado!");
				}
				
        	}catch (NumberFormatException ex){
        		JOptionPane.showMessageDialog(null, "Problema na Pesquisa do Setor, Verifique os Campos");
        		ex.printStackTrace();
        	} catch (ClassNotFoundException ex) {
        		JOptionPane.showMessageDialog(null, "Problema na Pesquisa do Setor");
        		ex.printStackTrace();
			} catch (SQLException ex) {
				JOptionPane.showMessageDialog(null, "Problema na Pesquisa do Setor no Banco.");
				ex.printStackTrace();
			}

		}
	}
	private MaskFormatter NovaMask(String in){
		
		MaskFormatter mask = new MaskFormatter();
		try{
		mask = new javax.swing.text.MaskFormatter(in);
		
		// maskPC.setPlaceholderCharacter('0');
		}catch (java.text.ParseException exp){
			System.out.println( "Problema na mascara. Informe ao suporte tecnico");
		}
		return mask;
	}
	private void AtivarBtnCancelar(){
		btnCancelar = new JButton("Cancelar");
		btnCancelar.setBounds(385, 185, 89, 23);
		contentPane.add(btnCancelar); // ativa o cancelar
		btnCancelar.setSelected(true);
		btnCancelar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
        		
				LimparTela();
        		BloquearCampos();
        		
			}
		});
	}
		
		
}
